/*
 * ConsoleManager.c
 *
 *  Created on: Mar 12, 2012
 *      Author: mikaelgra
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

#include "ConsoleManager.h"
#include "AlarmManager.h"
#include "ArrayList.h"
#include "Alarm.h"
#include "gpio/Define.h"

/**
 * Initializes the ConsoleManager. This must be called before
 * any other methods on the ConsoleManager.
 */
void ConsoleManager_Initialize()
{
	// any needed initialization logic
}


/**
 * Notifies the user that the alarm has been triggered and
 * prompts the user for a password.
 */
void ConsoleManager_PromptForPassword(struct stAlarm_t* alarm)
{
	// get current time!
	time_t startSeconds = time(NULL);

	char output[256];
	strcpy(output, "The alarm '");
	strcat(output, alarm->name);
	strcat(output, "' was triggered! \r\nEnter password (it is ");
	strcat(output, alarm->password);
	strcat(output, "): ");
	printf("%s", output);

	char input[32];
	gets(input);

	// check time
	time_t endSeconds = time(NULL);

	int seconds = endSeconds - startSeconds;

	if(seconds > alarm->triggerTime)
	{
		alarm->enAlarmState = eStarted;
		printf("%s", "Too much time used, starting alarm...\r\n");

		// SOUND OUTPUT!!!
		System_SetValue(alarm->gpioOutputPin, defPinHigh);

		ConsoleManager_PromptForPassword(alarm);
	}
	else if(!strcmp(input, alarm->password))
	{
		alarm->enAlarmState = eEnabled;
		printf("%s", "Alarm disabled!\r\n");

		// STOP SOUND OUTPUT
		System_SetValue(alarm->gpioOutputPin, defPinLow);
	}
	else
	{
		alarm->enAlarmState = eStarted;
		printf("%s", "Wrong password, starting alarm...\r\n");

		// SOUND OUTPUT!!!
		System_SetValue(alarm->gpioOutputPin, defPinHigh);

		ConsoleManager_PromptForPassword(alarm);
	}
}

/**
 * Finalizes the ConsoleManager stopping it, if necessary and
 * releasing all used resources.
 */
void ConsoleManager_Finalize()
{
	// any needed dispose logic
}
